package cmsc427.mw5.app;

import cmsc427.mw5.BluetoothChat;
import cmsc427.mw5.R;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class ScrollableWebView extends Activity {
	
	private static final String HOMEPAGE = "http://news.google.com";

	private WebView webView;
	private String url;
	private static MotionReceiver motionReceiver;
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.scrollable_web_view);
		
		url = HOMEPAGE;
		
		webView = (WebView) findViewById(R.id.webview);
		
		webView.setWebViewClient(new ScrollableWebViewClient());
		
		webView.getSettings().setJavaScriptEnabled(true);
		webView.loadUrl(url);
		
		// override the listener (for debug only)
		//webView.setOnKeyListener(new WebKeyListener());
		
		// register broadcast receivers
		motionReceiver = new MotionReceiver(this);
		registerReceiver(motionReceiver, new IntentFilter(BluetoothChat.BROADCAST_MOTION_ACTION));
	}
	
	
	private class ScrollableWebViewClient extends WebViewClient {
		
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url){
			view.loadUrl(url);
			return true;
		}
	}
	
	private static class MotionReceiver extends BroadcastReceiver {

    	private ScrollableWebView webView;
    	
    	public MotionReceiver(ScrollableWebView webView) {
    		this.webView = webView;
    	}
    	
		@Override
		public void onReceive(Context context, Intent intent) {			
			if(intent.getExtras().get(BluetoothChat.BROADCAST_MOTION_NAME).equals(BluetoothChat.BROADCAST_MOTION_UP)){
				webView.webView.pageUp(false);
			} else if(intent.getExtras().get(BluetoothChat.BROADCAST_MOTION_NAME).equals(BluetoothChat.BROADCAST_MOTION_DOWN)){
				webView.webView.pageDown(false);
			} else if(intent.getExtras().get(BluetoothChat.BROADCAST_MOTION_NAME).equals(BluetoothChat.BROADCAST_MOTION_LEFT)){
				if(webView.webView.canGoBack()){
					webView.webView.goBack();
				}
			} else if(intent.getExtras().get(BluetoothChat.BROADCAST_MOTION_NAME).equals(BluetoothChat.BROADCAST_MOTION_RIGHT)){
				context.unregisterReceiver(motionReceiver);
				webView.finish();
			}
			
		}
    	
    }
}
